package library.client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.xml.datatype.DatatypeConfigurationException;

import library.stub.Book;
import library.stub.LibraryServer;
import library.stub.LibraryServerService;

public class LibraryClient {
	private LibraryClientFrame frame;
	private LibraryServer libraryServer;

	public LibraryClient() {

		try {
			libraryServer = new LibraryServerService()
					.getPort(LibraryServer.class);

			frame = new LibraryClientFrame();
			frame.setVisible(true);
			frame.setSendListener(new SendMessageListener());

		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Connection failed", "Error",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	public static void main(String args[])
			throws DatatypeConfigurationException {
		new LibraryClient();
	}

	private class SendMessageListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					OperationType operation = frame.getMessageType();

					// Creo la richiesta a seconda dell'operazione selezionata
					// sull'interfaccia
					try {
						switch (operation) {
						case DELETE:
							String isdn = frame.getBookISDN();
							if (isdn.equals(""))
								frame.setErrorOnParameters();
							else {
								boolean res = libraryServer.deleteBook(isdn);
								if (res)
									frame.addConfirmationText("Book deleted successfully");
								else
									frame.addErrorText("Can't delete book. Check the isdn code.");
							}
							break;
						case INSERT:
							Book b = frame.getBookParameters();
							if (b==null || b.getISDN().equals(""))
								frame.setErrorOnParameters();
							else {
								boolean res = libraryServer.addBook(b);
								if (res)
									frame.addConfirmationText("Book added successfully");
								else
									frame.addErrorText("Can't add book. Check the isdn code.");
							}
							break;
						case SELECT:
							frame.setBooks(libraryServer.getAllBooks());
							break;
						default:
							break;

						}
					} catch (Exception e) {
						JOptionPane.showMessageDialog(null, "Connection failed", "Error",
								JOptionPane.ERROR_MESSAGE);
					}

				}

			}).start();
		}
	}
}
